import React, {useEffect, useRef} from 'react';
import {App, Button, Card, Form, Input, InputNumber, Select, Switch} from "antd";
import {Link, useNavigate, useParams} from "react-router-dom";
import LogFactory from "log/LogFactory";
import {requestGet} from "util/request";
import {SecurityPath} from "type/SecurityPath";
import TextArea from "antd/es/input/TextArea";
import {DefaultOptionType} from "rc-select/lib/Select";
import {compareObject} from "util/compare";
import {useAppDispatch} from "../../../redux/hook";
import {fetchUpdateData} from "../../../redux/reducer/pathReducer";

const log = LogFactory.getLog("PathUpdateComponent");
const PathUpdateComponent = () => {

    const {pathId} = useParams();
    const pathRef = useRef<SecurityPath>();
    const { message } = App.useApp();
    const dispatch = useAppDispatch() ;
    const navigate = useNavigate();
    const pathParentRef = useRef<SecurityPath[]>([]);
    const [option , setOption] = React.useState<DefaultOptionType[]>([]) ;
    const [form] = Form.useForm<SecurityPath>();

    useEffect(() => {
        requestGet<SecurityPath>("/manager/security-path/" + pathId)
            .then(res => {
                // log.requestDebug("获取路径数据", res);
                pathRef.current = res.data;
                form.setFieldsValue(res.data);
            });
        requestGet<SecurityPath[]>("/manager/security-path/list/parent")
            .then(res => {
                pathParentRef.current = res.data;
                setOption(res.data.map(e => {
                    return {
                        label: e.explain,
                        value: e.id
                    }
                })) ;
            });
    }, []);

    //TODO: 2021/4/7 0007 Select的onChange事件内容重复,需要抽取出来
    const selectOnChange = (value: number) => {
        log.debug("select-on-change: " , value) ;
        pathParentRef.current.forEach(e => {
            if (e.id === value){
                form.setFieldsValue({
                    pattern: e.pattern.replaceAll("*",""),
                }) ;
                return;
            }
            if (e.id === 0){
                form.setFieldsValue({
                    pattern: "/",
                }) ;
                return ;
            }
        })
    }

    const onFinish = async (value: SecurityPath) => {
        log.debug("提交修改" ,value) ;
        let compRes = compareObject(pathRef.current , value) ;
        if (compRes === null){
            log.debug("数据没有修改,不提交到服务器") ;
            message.info("数据没有修改,不提交到服务器") ;
            return ;
        }else {
            compRes.id = pathRef.current?.id ;
            let res = await dispatch(fetchUpdateData(compRes)).unwrap().then(res => res) ;
            if (res > 0) {
                log.debug("修改路径数据成功") ;
                message.success("修改路径数据成功") ;
                navigate("",{replace:true}) ;
            }else {
                log.debug("修改路径数据失败") ;
                message.info("修改路径数据失败") ;
            }
        }
    }

    return (
        <Card
            title={"更新路径"}
            extra={<Link key={"path-list"} to={""}>路径列表</Link>}
        >
            <Form<SecurityPath>
                form={form}
                layout={"horizontal"}
                labelCol={{span: 6}}
                wrapperCol={{span: 12}}
                onFinish={onFinish}
            >
                <Form.Item<SecurityPath> label="父路径" name={"parentId"}>
                    <Select
                        loading={false}
                        options={option}
                        maxLength={3}
                        onChange={selectOnChange}
                    />
                </Form.Item>
                <Form.Item<SecurityPath> label="路径模式" name={"pattern"}>
                    <Input/>
                </Form.Item>
                <Form.Item<SecurityPath> label="路径描述" name={"explain"}>
                    <Input/>
                </Form.Item>
                <Form.Item<SecurityPath> label="子路径" name={"last"}>
                    <Switch/>
                </Form.Item>
                <Form.Item<SecurityPath> label="请求方法" name={"method"}>
                    <Select>
                        <Select.Option value="GET">GET 请求</Select.Option>
                        <Select.Option value="POST">POST 请求</Select.Option>
                        <Select.Option value="PUT">PUT 请求</Select.Option>
                        <Select.Option value="DELETE">DELETE 请求</Select.Option>
                        <Select.Option value="ANY">任何请求</Select.Option>
                        <Select.Option value="DEFAULT">默认请求</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item<SecurityPath> name="order" label="数据排序">
                    <InputNumber min={0}/>
                </Form.Item>
                <Form.Item<SecurityPath> name={"remark"} label="备注信息">
                    <TextArea rows={5}/>
                </Form.Item>
                <Form.Item wrapperCol={{offset: 8, span: 16}}>
                    <Button type="primary" htmlType="submit">提交修改</Button>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default PathUpdateComponent;